<template>
     <div>
       <el-upload
          action="/api/merchant/file/uploadImg"
         :class="{ isDisplayPic: imgageList.length >= imageSize }"
         :httpRequest="uploadImage"
         :before-upload="beforeFileUpload"
         list-type="picture-card"
         :limit="imageSize"
         :file-list="fileList"
       >
         <i class="el-icon-plus ic_plus"></i>
         <div slot="file" slot-scope="{file}">
           <img
             class="el-upload-list__item-thumbnail"
             :src="file.url" alt=""
           >
           <span class="el-upload-list__item-actions">
             <span
               class="el-upload-list__item-preview"
               @click="handlePictureCardPreview(file)"
             >
               <i class="el-icon-zoom-in"></i>
             </span>
             <!-- <span
               v-if="!disabled"
               class="el-upload-list__item-delete"
               @click="handleDownload(file)"
             >
               <i class="el-icon-download"></i>
             </span> -->
             <span
               class="el-upload-list__item-delete"
               @click="handleGoodsFileRemove(file)"
             >
               <i class="el-icon-delete"></i>
             </span>
           </span>
         </div>
         <!-- <el-progress v-if="videoFlag == true" type="circle"
              v-bind:percentage="videoUploadPercent"
              style="margin-top: 7px"></el-progress> -->
       </el-upload>
       <p><span>{{titlMsg}}</span></p>
       <el-dialog :visible.sync="dialogVisible" append-to-body>
         <img width="100%" :src="dialogImageUrl" alt="">
       </el-dialog>
     </div>
</template>
<script>
import axios from 'axios'
import UploadType from "./res-type";
import { upload as uploadImage,deletePic as deleteFile } from '@/api/file'
export default {
  name: 'YuguUpload',
  props: {
    imageSize:{
      type:Number,
      default:1
    },
    type:{
      type: String,
      default: UploadType.IMAGE,
      validator: function (value) {
        return [UploadType.IMAGE, UploadType.VIDEO].indexOf(value) !== -1;
      }
    },
    videoLimitSize: {
      type: Number,
      default: 10 // 以M为单位
    },
    imageLimitSize: {
      type: Number,
      default: 2 // 以M为单位
    },
    imgageList:{
      type:Array,
      default: () => []
    }
  },
  data() {
      return {
        imageApi: process.env.VUE_APP_IMAGE_API,
        headers: {},
        fileList:[],
        dialogImageUrl:'',
        dialogVisible:false
  }},
  computed: {
    titlMsg() {
      if(this.type=='image'){
        return '每张图片大小不超过'+this.imageLimitSize+'M，数量不超过'+this.imageSize+'张';
      }else if(this.type=="video"){
        return '每条视频大小不超过'+this.videoLimitSize+'M，数量不超过'+this.imageSize+'条';
      }
    }
  },
  mounted(){
    console.log('111',this.imgageList)
  },
  methods: {
    init(files){
      this.fileList=files
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleGoodsFileRemove (file) {
      let filePath = file.filePath
      if (filePath) {
        deleteFile(filePath,file.id).then(res => {

        })
      }
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeFileUpload (file, fileList) {
      return new Promise((resolve, reject) => {
                // const isJpgOrPng = file.type === 'image/jpeg'  //这里获取上传文件的类型
                // if (!isJpgOrPng) {
                //   this.$message.warning('请上传jpg图片')
                //   return reject(false);  //如有问题那咱们通过reject 函数传一个false阻止他的上传
                // }
                if(this.type=='image'){
                  var fileNames = file.name.split('.')
                  var fileType = fileNames[fileNames.length - 1].toLocaleLowerCase()
                  var extList = ['bmp', 'png', 'jpeg', 'jpg', 'gif']
                  if (!extList.find((item) => item == fileType)) {
                    this.$message.error('只能上传.bmp/.png/.jpeg/.jpg/gif类型的图片！')
                    reject(false)
                  }
                  // if(['bmp', 'png', 'jpeg', 'jpg', 'gif'].indexOf(file.type) == -1) {
                  //        this.$message.error('只能上传.bmp/.png/.jpeg/.jpg/gif类型的图片！');
                  //        return reject(false);
                  // }
                  const isLt2M = file.size / 1024 / 1024 < this.imageLimitSize; // 2M
                  if (!isLt2M) {
                    this.$message.error( "每张图片大小不能超过 "+this.imageLimitSize+"MB!");
                    return reject(false);
                  }else{
                    this.loading = true
                    return resolve(true)
                  }
                }else if(this.type=='video'){
                    if(['video/mp4', 'video/ogg', 'video/wmv'].indexOf(file.type) == -1) {
                           this.$message.error('请上传正确的视频格式');
                           return reject(false);
                    }
                    const isLt10M = file.size / 1024 / 1024 < this.videoLimitSize; // 10M
                    if (!isLt10M) {
                      this.$message.error("每条视频大小不能超过 "+this.videoLimitSize+"MB!");
                       return reject(false);
                    }else{
                      this.loading = true
                      return resolve(true)
                    }
                }
              });
    },
    handleChange ({ fileList }) {
      this.fileList = fileList
    },
    uploadImage (files) {
      const fileItem = {
        uid: files.file.uid, // 注意，这个uid一定不能少，否则上传失败
        name: files.file.name,
        status: 'uploading',
        url: '',
        percent: 50, // 注意不要写100。100表示上传完成
      }
      let formData = new FormData();
      formData.append( "file", files.file);
      uploadImage(formData).then((res)=>{
        if (res.httpCode === 200) {
            fileItem.uid=res.data.planFlieId,
            fileItem.status = "done";
            fileItem.name = res.data.fileName;
            fileItem.url = process.env.VUE_APP_IMAGE_BASE_URL+res.data.path;
            fileItem.filePath = res.data.path;// imgUrl 是存到 db 里的相对链接
            fileItem.extName = res.data.extName;// imgUrl 是存到 db 里的相对链接
            fileItem.fileSize = res.data.fileSize;// imgUrl 是存到 db 里的相对链接
            this.$message.success("上传成功！");
          } else {
            fileItem.status = "error";
            fileItem.response = res.msg;
            this.$message.error("上传失败！");
          }
          this.fileList.push(fileItem) // 更新 imgList
      }).catch((err)=>{
        return Promise.resolve(err);
      })
    }
    },
    watch: {
      fileList:{
        handler(newVal,oldVal){
              this.$emit('updateImg', newVal)
            },
            immediate:true
      },
      imgageList(val){
        this.fileList=val
      }
    }
}
</script>
<style lang="scss">
.displayPic > .el-upload--picture-card {
  display: none;
}
.isDisplayPic > .el-upload--picture-card {
  display: none;
}
.handle_btn {
  margin: 20px 0;
  display: flex;
  align-items: center;

  .search_input {
    width: 180px;
    margin-right: 20px;
  }
  .btn_click {
    margin-right: 20px;
  }
}
.goods_name {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.goods_pic {
  width: 100%;
  height: 60px;
  overflow: hidden;

  & > img {
    width: 100%;
  }
}
</style>


